import 'package:flutter/material.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/servers/question_type.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';

class CategoryFilter extends StatefulWidget {
  final List<QuestionType> categoryList;
  final int sort;
  final int currentIndex;
  final ValueChanged<int> onSortChanged; // 排序变化的回调
  final ValueChanged<int> onIndexChanged; // 索引变化的回调

  const CategoryFilter({
    super.key,
    required this.categoryList,
    required this.sort,
    required this.currentIndex, 
    required this.onSortChanged, 
    required this.onIndexChanged,
  });

  @override
  State<CategoryFilter> createState() => _CategoryFilterState();
}

class _CategoryFilterState extends State<CategoryFilter> {
  late int selectedSort; // 当前选中的排序
  late int selectedSortIndex; // 当前选中的类别索引
  late int selectedCategoryIndex; // 当前选中的类别索引


  // 题目排序
  final List<Map<String, dynamic>> sortList = [
    {"name": "默认", "type": "default" , "value":AppEnumSortType.sortDefault },
    {"name": "推荐", "type": "default"  , "value":AppEnumSortType.sortCommend },
    {"name": "浏览量", "type": "count"  , "value":AppEnumSortType.sortViewLow},
    {"name": "难度", "type": "count" , "value":AppEnumSortType.sortDifficultyLow}
  ];

  @override
  void initState() {
    super.initState();
    _initializeState();
  }

   @override
  void didUpdateWidget(covariant CategoryFilter oldWidget) {
    super.didUpdateWidget(oldWidget);
    Logger.info("查看旧状态 $oldWidget.sort  ; 新状态$widget.sort" , tag: "didUpdateWidget");
    // 检查父组件的参数是否发生了变化
    if (widget.sort != oldWidget.sort || widget.currentIndex != oldWidget.currentIndex) {
      _initializeState(); // 更新状态
    }
  }

    /// 初始化组件状态
  void _initializeState() {
    selectedSort = widget.sort; // 初始化为父组件传递的 sort
    selectedSortIndex = sortList.indexWhere((sort) => sort['value'] == widget.sort);
    selectedSortIndex = selectedSortIndex == -1 ? 0 : selectedSortIndex;
    selectedCategoryIndex = widget.currentIndex;
  }


  /// 处理排序选项点击
  void _handleSortSelection(int index, int? value, String? name) {
    setState(() {
      selectedSortIndex = index;
      // 根据排序类型切换升序/降序
      if (name == "浏览量") {
        selectedSort = (selectedSort == AppEnumSortType.sortViewLow)? AppEnumSortType.sortViewHigh: AppEnumSortType.sortViewLow;
      } else if (name == "难度") {
        selectedSort = (selectedSort == AppEnumSortType.sortDifficultyLow) ? AppEnumSortType.sortDifficultyHigh : AppEnumSortType.sortDifficultyLow;
      } else {
        selectedSort = value!;
      }
      widget.onSortChanged(selectedSort); // 通知父组件更新状态
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).extension<AppColors>()!;
    return Container(
      padding: const EdgeInsets.only(top: 4, left: 16, right: 16, bottom: 16),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _filterTypeColumn(
            title: "题目排序",
            items: sortList.map((item) => item["name"] as String ).toList(),
            types: sortList.map((item) => item["type"] as String ).toList(),
            values: sortList.map((item) => item["value"] as int ).toList(),
            isFlagVisible: false,
            onTagSelected:_handleSortSelection,
            isSelected: (index) => selectedSortIndex == index ,
            theme:theme
          ),
          const SizedBox(height: 12),
          _filterTypeColumn(
            title: "选择阶段",
            items: widget.categoryList.map((item) => item.name).toList(),
            isFlagVisible: true,
            flags: widget.categoryList.map((item) => item.displayNewestFlag == 1).toList(),
            theme:theme,
            onTagSelected: (index, _ , name) {
              setState(() {
                selectedCategoryIndex = index; // 更新选中的类别
                widget.onIndexChanged(selectedCategoryIndex);
              });
            },
            isSelected: (index) => selectedCategoryIndex == index,
          ),
        ],
      ),
    );
  }

  Widget _filterTypeColumn({
    required String title,
    required List<String> items, // 标签名称列表
    List<int>? values, // values列表
    List<String>? types, // 标签类型
    bool isFlagVisible = false, // 是否显示 newest 标志
    List<bool>? flags, // newest 标志
    required Function(int index, int? value , String?name) onTagSelected, // 点击回调
    required bool Function(int index) isSelected, // 是否选中的回调
    required theme
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _title(text: title),
        const SizedBox(height: 6),
        Wrap(
          spacing: 12,
          runSpacing: 8,
          children: List.generate(items.length, (index) {
            final type = types != null ? types[index] : null;
            return _filterTag(
              theme:theme,
              text: items[index],
              showNewest: isFlagVisible && (flags?[index] ?? false),
              type: type,
              isSelected: isSelected(index),
              onTap: () => onTagSelected(index, values?[index] , items[index]),
            );
          }),
        ),
      ],
    );
  }


  Widget _filterTag({
    required String text,
    required AppColors theme,
    bool showNewest = false,
    String? type,
    bool isSelected = false, // 是否被选中
    Function()? onTap, // 标签点击事件回调
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: theme.subjectMix2,
              borderRadius: BorderRadius.circular(6), // 设置圆角
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  text,
                  style: TextStyle(
                    fontSize: 12,
                    color: isSelected ? Colors.orange : theme.contrastMix3, // 选中变橙色
                    fontWeight: isSelected? FontWeight.bold : FontWeight.normal
                  ),
                ),
                if (type == "count")
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                     Icon(
                        Icons.keyboard_arrow_up,
                        color:(isSelected && selectedSort.isEven)  ? Colors.orange : theme.contrastMix3, // 选中变橙色
                        size: 10,
                      ),
                    Icon(
                      Icons.keyboard_arrow_down,
                      color:(isSelected &&   selectedSort.isOdd) ? Colors.orange : theme.contrastMix3, // 选中变橙色
                      size: 10,
                    ),
                  ],
                )
              ],
            ),
          ),
          if (showNewest)
            Positioned(
              right: -10,
              top: -9,
              child: Image.asset(
                '${AppEnumAssets.basePath}ic_home_new.png',
                width: 30,
                height: 18,
              ),
            ),
        ],
      ),
    );
  }

  static Widget _title({required String text}) {
    return Text(
      text,
      style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
    );
  }
}
